/**
 * @file dbcollection.c
 * @brief Fichier source du module dbcollection.
 *
 * @author Rachid Delory, Mamadou Keita, Florian Bernard
 */

/* *********************************************************************

                       Librairies de database

********************************************************************* */

#include "dbcollection.h"

/* *********************************************************************

                        Fonctions

********************************************************************* */
void recuperation_DCol(Collection **collection, const int id)
{
  if((*collection) && id > 0)
    {
      DataBase data;
      ouvrir_Db();
      /* Récupération de ceux qui ont comme père id */
      prepare_Db(&data, "select rowid, libelle, nbLivre from collection where rowid = ?");
      bindValueInt_Db(&data, 1, id);

      while(execute_Db(&data))
	{
	  if((*collection) == NULL)
	    (*collection) = creer_Col();
	  setId_Col((*collection), getValueInt_Db(&data, 0));
	  setLibelle_Col((*collection), getValueText_Db(&data, 1));
	  setNbLivre_Col((*collection), getValueInt_Db(&data, 2));
	}
      finalise_Db(&data);
    }
}

void insertion_DCol(Collection *collection)
{
  if(collection)
    {
      DataBase data;
      ouvrir_Db();
      if(getId_Col(collection) == 0)
	{
	  prepare_Db(&data, "insert into collection (libelle, nbLivre) values (?, ?)");
	}
      else
	{
	  prepare_Db(&data, "update collection set libelle = ?, nbLivre = ? where rowid = ?");
	  bindValueInt_Db(&data, 3, getId_Col(collection));
	}
      bindValueText_Db(&data, 1, getLibelle_Col(collection));
      bindValueInt_Db(&data, 2, getNbLivre_Col(collection));

      if(execute_Db(&data))
	{

	}
      finalise_Db(&data);
      if(getId_Col(collection) == 0)
	{
	  prepare_Db(&data, "select max(rowid) from collection");
	  if(execute_Db(&data))
	    {
	      setId_Col(collection, getValueInt_Db(&data, 0));
	    }
	  finalise_Db(&data);
	}
    }
}

void suppression_DCol(const int id)
{
  if(id > 0)
  {
    DataBase data;
    ouvrir_Db();
    prepare_Db(&data, "delete from collection where rowid = ?");
    bindValueInt_Db(&data, 1, id);
    if (execute_Db(&data))
      {
	
      }
    finalise_Db(&data);
    prepare_Db(&data, "update Livre set id_collection = 0 where id_collection = ?");
    bindValueInt_Db(&data, 1, id);
    if (execute_Db(&data))
      {
	
      }
    finalise_Db(&data);
  }
}
